package com.xydtech.ecard.ecard.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xydtech.common.EcardOrgInfoApiCommon;
import com.xydtech.common.annotation.PassToken;
import com.xydtech.common.annotation.RsaRequest;
import com.xydtech.common.core.domain.entity.SysDept;
import com.xydtech.common.enums.ResultStatus;
import com.xydtech.common.model.ResponseModel;
import com.xydtech.common.utils.DateUtils;
import com.xydtech.common.utils.GeoUtil;
import com.xydtech.common.utils.StringUtils;
import com.xydtech.common.utils.sql.SqlUtil;
import com.xydtech.common.utils.string.StringUtil;
import com.xydtech.ecard.config.service.IEcardApiSysConfigService;
import com.xydtech.ecard.ecard.domain.*;
import com.xydtech.ecard.ecard.service.*;
import com.xydtech.ecard.imp.domain.EcardMerchantImport;
import com.xydtech.ecard.imp.domain.EcardMerchantImportTask;
import com.xydtech.ecard.imp.service.IEcardMerchantImportService;
import com.xydtech.ecard.imp.service.IEcardMerchantImportTaskService;
import com.xydtech.ecard.merchant.domain.*;
import com.xydtech.ecard.merchant.service.IEcardBranchEcardChartService;
import com.xydtech.ecard.merchant.utils.JWDUtils;
import com.xydtech.ecard.merchant.utils.JqPoint;
import com.xydtech.ecard.user.domain.EcardApiEcardRegistInfo;
import com.xydtech.ecard.user.domain.EcardApiUserInfo;
import com.xydtech.ecard.user.service.IEcardApiEcardRegistInfoService;
import com.xydtech.ecard.user.service.IEcardApiUserService;
import com.xydtech.system.domain.SysConfig;
import com.xydtech.system.domain.SysWechatApplet;
import com.xydtech.system.service.ISysConfigService;
import com.xydtech.system.service.ISysDeptService;
import com.xydtech.system.service.ISysWechatAppletService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 电子名片-商户营销接口类
 * 说明：商户相关接口改为多个商户类型（1-个人，2-商户，3-企业，4-新型农业主体）操作
 * 在接口方法上加上单用、公用（传商户类型字段来判断操作业务）区分
 * @author yjs
 * @date 2023/7/22 11:27
 */

@Controller
@Slf4j
@Api(tags = "电子名片-商户营销接口")
@RequestMapping("/ecardSaasApi/merchantMarketing")
public class EcardMerchantMarketingController extends EcardApiBaseController {
    //4:客户经理
    private static String roles = "4";
    //客户经理岗位，后台没维护，这里用不到
    private static String cm = "cm";
    //网格管理员岗位
    private static String wg = "wg";

    @Autowired
    private IEcardApiUserService ecardApiUserService;
    @Autowired
    private ISysWechatAppletService wechatAppletService;
    @Autowired
    private IEcardApiPersonInfoService ecardPersonInfoService;
    @Autowired
    private IEcardApiMerchantInfoService ecardMerchantInfoService;
    @Autowired
    private IEcardApiEnterpriseInfoService ecardEnterpriseInfoService;
    @Autowired
    private IEcardApiAgricultureInfoService ecardAgricultureInfoService;
    @Autowired
    private IEcardApiMerchantTaskService ecardApiMerchantTaskService;
    @Autowired
    private IEcardApiMerchantPartInfoService ecardMerchantPartInfoService;
    @Autowired
    private IEcardApiMerchantVisitInfoService ecardMerchantVisitInfoService;
    @Autowired
    private IEcardApiMerchantReservationTaskService ecardApiMerchantReservationTaskService;
    @Autowired
    private IEcardApiSysConfigService ecardApiSysConfigService;
    @Autowired
    private IEcardApiEcardRegistInfoService registInfoService;
    @Autowired
    private IEcardBranchEcardChartService ecardBranchEcardChartService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private EcardOrgInfoApiCommon ecardOrgInfoApiCommon;
    @Autowired
    private IEcardMerchantImportTaskService ecardMerchantImportTaskService;
    @Autowired
    private IEcardMerchantImportService ecardMerchantImportService;

    /**
     * 电子名片-条件查询登录人名下商户列表接口（单用）
     *
     * @param: search 查询条件
     * @author yjs
     * @date 2023/7/26 9:08
     */
    @PostMapping(value = "/getMyMerchantList")
    @ApiOperation(value = "电子名片-条件查询登录人名下商户列表接口", notes = "电子名片-条件查询登录人名下商户列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMyMerchantInfoList(@RequestBody String json) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            JSONObject jsonObject = JSONObject.parseObject(json);
            String search = jsonObject.getString("search");//查询条件姓名和手机号拆开
            String phone = jsonObject.getString("phone");
            Integer industry = jsonObject.getInteger("industry");
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");

            EcardApiMerchantInfo ecardMerchantInfo = new EcardApiMerchantInfo();
            ecardMerchantInfo.setHandName(search);
            ecardMerchantInfo.setContactsPhone(phone);
            ecardMerchantInfo.setIndustry(industry);
            ecardMerchantInfo.setCreatorId(Long.valueOf(currentUserId));
            ecardMerchantInfo.setDictDeptId(wechatApplet.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardApiMerchantInfo> merchantList = ecardMerchantInfoService.getMyMerchantInfoList(ecardMerchantInfo, salt);
            List<EcardApiMerchantInfo> apiMerchantList = new ArrayList<>();
            PageInfo pageInfo = new PageInfo(merchantList);
            for (EcardApiMerchantInfo merchant : merchantList) {
                //查询总拜访次数
                EcardApiMerchantVisitInfo merchantVisitInfo = new EcardApiMerchantVisitInfo();
                merchantVisitInfo.setMerchantId(merchant.getId());
                merchantVisitInfo.setMerchantType("2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                List<EcardApiMerchantVisitInfo> visitInfoList = ecardMerchantVisitInfoService.getMerchantVisitList(merchantVisitInfo);
                merchant.setVisitNumber(visitInfoList.size() + "");

                //查询最近一次拜访时间
                String lastVisitTime = ecardMerchantVisitInfoService.getMerchantLastVisitTime(merchant.getId(),"2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                if (StringUtils.isNotEmpty(lastVisitTime)) {
                    merchant.setLastVisitDate(DateUtils.parseDate(lastVisitTime));
                }
                apiMerchantList.add(merchant);
            }
            log.info("接口返回时间-------" + DateUtils.getTime());
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), apiMerchantList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-条件查询商户列表接口（单用）
     *
     * @param: type 1登录人所在机构下全部，2法人机构下全部（针对网格管理岗位）
     * @param: search 查询条件
     * @author yjs
     * @date 2023/7/26 9:08
     */
    @PostMapping(value = "/getMerchantList")
    @ApiOperation(value = "电子名片-条件查询商户列表接口", notes = "电子名片-条件查询商户列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantList(@RequestBody String json) {
        log.info("接口请求时间-------" + DateUtils.getTime());
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            //查询客户经理信息
            EcardApiEcardRegistInfo ecardApiEcardRegistInfo = registInfoService.selectEcardApiEcardRegistInfoByRegistId(Long.valueOf(currentUserId), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            String type = jsonObject.getString("type");
            String search = jsonObject.getString("search");//查询条件姓名和手机号拆开
            Integer industry = jsonObject.getInteger("industry");
            String sortTime = jsonObject.getString("sortTime");
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");

            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            EcardApiMerchantInfo ecardMerchantInfo = new EcardApiMerchantInfo();
            ecardMerchantInfo.setHandName(search);
            ecardMerchantInfo.setIndustry(industry);
            ecardMerchantInfo.setSortTime(sortTime);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            ecardMerchantInfo.setDictDeptId(wechatApplet.getDeptId());
            if (ecardApiEcardRegistInfo != null) {
                boolean postFlag = false;
                //多个岗位判断，只要有网格管理就传法人机构
                if (!StringUtils.objIsNullOrEmpty(userInfo.getExtendPostCode())) {
                    for (String extendPost : userInfo.getExtendPostCode().split(",")) {
                        if (wg.equals(extendPost)) {
                            postFlag = true;
                        }
                    }
                }
                if (roles.equals(ecardApiEcardRegistInfo.getRoles())) {
                    if ("1".equals(type) && !postFlag) {
                        ecardMerchantInfo.setDeptId(userInfo.getDeptId());
                        //查询是否有子部门
                        int deptNum = sysDeptService.selectNormalChildrenDeptById(userInfo.getDeptId());
                        if(deptNum == 0){
                            ecardMerchantInfo.setDeptFlag("2");
                        }else {
                            ecardMerchantInfo.setDeptFlag("3");
                        }
                    } else if (postFlag) {
                        ecardMerchantInfo.setDeptId(wechatApplet.getDeptId());
                        ecardMerchantInfo.setDeptFlag("1");
                    } else {
                        return ResponseModel.error("操作人岗位不正确,请联系管理员！");
                    }
                } else {
                    return ResponseModel.error("您没有查看商户列表的权限！");
                }
            } else {
                return ResponseModel.error("用户信息不存在！");
            }


            PageHelper.startPage(pageNum, pageSize);
            List<EcardApiMerchantInfo> merchantList = ecardMerchantInfoService.getMerchantList(ecardMerchantInfo);
            PageInfo pageInfo = new PageInfo(merchantList);
            log.info("接口返回时间-------" + DateUtils.getTime());
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), merchantList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询地图坐标列表接口（单用）
     *
     * @param: type 1登录人所在机构下全部，2法人机构下全部（针对网格管理岗位）
     * @author yjs
     * @date 2023/7/27 16:24
     */
    @PostMapping(value = "/getMerchantCoordinateList")
    @ApiOperation(value = "电子名片-查询商户地图坐标列表接口", notes = "电子名片-查询商户地图坐标列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantCoordinateList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            JSONObject jsonObject = JSONObject.parseObject(json);
            String type = jsonObject.getString("type");
            Integer industry = jsonObject.getInteger("industry");
            String coordinate = jsonObject.getString("coordinate");

            SysConfig config = new SysConfig();
            config.setConfigKey("ecard_merchant_show_distance");
            SysConfig sysConfig;

            if (StringUtils.objIsNullOrEmpty(currentUserId) || StringUtils.objIsNullOrEmpty(type)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            List<EcardApiMerchantInfo> merchantInfoList;

            if ("1".equals(type)) {
                //获取当前用户的信息
                EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
                merchantInfoList = ecardMerchantInfoService.getMerchantCoordinateList(Long.valueOf(currentUserId), userInfo.getDeptId(), industry);
                SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
                config.setDeptId(sysDept.getDeptId());
                sysConfig = ecardApiSysConfigService.selectConfig(config);
            } else {
                EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
                //当前小程序id
                SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
                merchantInfoList = ecardMerchantInfoService.getAllMerchantCoordinateList(Long.valueOf(currentUserId), wechatApplet.getDeptId(), industry);
                SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(wechatApplet.getDeptId());
                config.setDeptId(sysDept.getDeptId());
                sysConfig = ecardApiSysConfigService.selectConfig(config);
            }

            //有经纬度就计算，没有取全部
            if (coordinate != null) {
                List<EcardApiMerchantInfo> list = new ArrayList<>();
                //计算是否在配置的范围之内
                //定位的商户经纬度
                String place[] = coordinate.split(",");
                for (EcardApiMerchantInfo ecardApiMerchantInfo : merchantInfoList) {
                    String clockInPlace[] = ecardApiMerchantInfo.getCoordinate().split(",");
                    Double distance = GeoUtil.GetDistance(Double.valueOf(clockInPlace[1]), Double.valueOf(clockInPlace[0]), Double.valueOf(place[1]), Double.valueOf(place[0]));

                    BigDecimal bigDistance = new BigDecimal(distance);
                    BigDecimal bigValue = new BigDecimal(sysConfig.getConfigValue());
                    if (bigDistance.compareTo(bigValue) <= 0) {
                        list.add(ecardApiMerchantInfo);
                    }
                }

                return ResponseModel.okToJSONArray(list);
            } else {
                return ResponseModel.okToJSONArray(merchantInfoList);
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询商户详情接口（单用）
     *
     * @author yjs
     * @date 2023/7/26 10:33
     */
    @PostMapping("/getMerchantInfo")
    @ApiOperation(value = "电子名片-查询商户详情接口", notes = "电子名片-查询商户详情接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantInfo(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiEcardRegistInfo ecardApiEcardRegistInfo = registInfoService.selectEcardApiEcardRegistInfoByRegistId(Long.valueOf(currentUserId), salt);
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);

            if (!roles.equals(ecardApiEcardRegistInfo.getRoles())) {
                return ResponseModel.error("您没有查看该商户的权限！");
            }

            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            //根据商户id查询商户成员信息
            EcardApiMerchantPartInfo apiMerchantPartInfo = new EcardApiMerchantPartInfo();
            apiMerchantPartInfo.setMerchantId(id);
            apiMerchantPartInfo.setMerchantType("2");
            List<EcardApiMerchantPartInfo> merchantPartList = ecardMerchantPartInfoService.selectEcardMerchantPartInfoList(apiMerchantPartInfo, salt);//商户类型：1-个人，2-商户，3-企业，4-新型农业主体

            EcardApiMerchantInfo merchantInfo = ecardMerchantInfoService.selectEcardMerchantInfoById(id, salt);
            if (merchantPartList.size() > 0) {
                merchantInfo.setEcardApiMerchantPartInfos(merchantPartList);
            }
            return ResponseModel.okToJSON(merchantInfo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-保存商户数据接口,只有客户经理能保存商户信息（单用）
     *
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/addMerchantInfo")
    @ApiOperation(value = "电子名片-保存商户数据接口", notes = "电子名片-保存商户数据接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel addMerchantInfo(@RequestBody EcardApiMerchantInfo ecardMerchantInfo) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            Long merchantId = ecardMerchantInfo.getId();//商户id
            boolean flag = false;//判断是新增还是编辑
            EcardApiEcardRegistInfo ecardApiEcardRegistInfo = registInfoService.selectEcardApiEcardRegistInfoByRegistId(Long.valueOf(currentUserId), salt);
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            if (!roles.equals(ecardApiEcardRegistInfo.getRoles())) {
                return ResponseModel.error("您没有编辑商户信息的权限！");
            }
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            //当前登录人ID
            ecardMerchantInfo.setCreatorId(Long.valueOf(currentUserId));
            //登录人机构ID
            ecardMerchantInfo.setDeptId(userInfo.getDeptId());
            if (!StringUtils.isNotNull(ecardMerchantInfo.getId())) {
                int count = ecardMerchantInfoService.validateMerchantInfo(ecardMerchantInfo);
                if (count > 0) {
                    return ResponseModel.error("相同行业、支行、门头名不能重复！");
                }
                flag = true;
            } else {
                //校验是否是自己的商户
                EcardApiMerchantInfo ecardApiMerchantInfo = ecardMerchantInfoService.selectEcardMerchantInfoById(ecardMerchantInfo.getId(), salt);
                if (ecardApiMerchantInfo != null) {
                    if (ecardApiMerchantInfo.getCreatorId().longValue() != ecardApiEcardRegistInfo.getRegistId().longValue()) {
                        ResponseModel.error("您没有编辑该商户信息的权限！");
                    }
                } else {
                    return ResponseModel.error("操作失败，未查询到该商户信息！");
                }
                flag = false;
            }
            int id = ecardMerchantInfoService.addMerchantInfo(ecardMerchantInfo, salt);
            //处理成员信息（新增/编辑）
            List<EcardApiMerchantPartInfo> ecardApiMerchantPartInfos = ecardMerchantInfo.getEcardApiMerchantPartInfos();
            if (ecardApiMerchantPartInfos.size() > 0) {
                for (EcardApiMerchantPartInfo ecardMerchantPartInfo : ecardApiMerchantPartInfos) {
                    if (!StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getIdCard())) {
                        EcardApiMerchantPartInfo merchantPartInfo = new EcardApiMerchantPartInfo();
                        merchantPartInfo.setMerchantId(ecardMerchantPartInfo.getMerchantId());
                        merchantPartInfo.setIdCard(ecardMerchantPartInfo.getIdCard());
                        merchantPartInfo.setMerchantType("2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                        List<EcardApiMerchantPartInfo> partInfoList = ecardMerchantPartInfoService.selectEcardMerchantPartInfoList(merchantPartInfo, salt);
                        if (partInfoList != null && partInfoList.size() > 0) {
                            //判断是新增还是编辑
                            if (StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getId())) {
                                return ResponseModel.error("成员信息已存在！");
                            } else {
                                if (!partInfoList.get(0).getId().equals(ecardMerchantPartInfo.getId())) {
                                    return ResponseModel.error("成员信息已存在！");
                                }
                            }
                        }
                    }

                    //查询商户人员是否存在
                    if (!StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getId())) {
                        EcardApiMerchantPartInfo ecardApiMerchantPartInfo = ecardMerchantPartInfoService.selectEcardMerchantPartInfoById(ecardMerchantPartInfo.getId(), salt);
                        if (ecardApiMerchantPartInfo == null) {
                            return ResponseModel.error("成员信息不存在，请核实！");
                        }
                    }

                    //当前登录人Id
                    ecardMerchantPartInfo.setCreatorId(Long.valueOf(currentUserId));
                    ecardMerchantPartInfo.setMerchantType("2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                    if (flag) {//新增时取保存完企业返回的商户id，编辑时取传参的商户id
                        ecardMerchantPartInfo.setMerchantId(ecardMerchantInfo.getId());
                    } else {
                        ecardMerchantPartInfo.setMerchantId(merchantId);
                    }
                    //添加时根据商户id和商户类型判断有没有成员，没有把是否联系人字段改为是，有不操作
                    List<EcardApiMerchantPartInfo> ecardMerchantPartInfos = ecardMerchantPartInfoService.getMerchantPartList(ecardMerchantPartInfo.getMerchantId(), "2", wechatApplet.getDeptId(), salt);
                    if (ecardMerchantPartInfos.size() == 0) {
                        ecardMerchantPartInfo.setIsContacts("T");
                    }
                    ecardMerchantPartInfoService.addMerchantPartInfo(ecardMerchantPartInfo, salt);
                }
            }
            //新增时添加首次拜访任务
            if (flag) {
                //查询参数配置-拜访任务定时天数
                SysConfig config = new SysConfig();
                config.setConfigKey("ecard_merchant_task_days");
                SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
                config.setDeptId(sysDept.getDeptId());
                SysConfig sysConfig = ecardApiSysConfigService.selectConfig(config);
                int taskDays = Integer.valueOf(sysConfig.getConfigValue());//拜访任务定时天数
                /**
                 * 保存商户时新增一条拜访任务，下次回访日期默认为当前日期加拜访任务定时天数
                 */
                Date nextDay = DateUtils.getNextDay(new Date(), taskDays);
                Date endDate = DateUtils.formatDate(nextDay, DateUtils.YYYY_MM_DD);
                EcardApiMerchantTask merchantTask = new EcardApiMerchantTask();
                merchantTask.setMerchantId(ecardMerchantInfo.getId());
                merchantTask.setCmRegistId(ecardMerchantInfo.getCreatorId());
                merchantTask.setMerchantType("2");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                merchantTask.setEndDate(endDate);
                merchantTask.setTaskSts("0");
                ecardApiMerchantTaskService.insertEcardMerchantTask(merchantTask);
                //新增商户信息时，校验是否从批量导入任务跳转过来，如果是批量跳转任务，则修改任务为完成
                if(!StringUtil.objIsNullOrEmpty(ecardMerchantInfo.getTaskId())){

                    EcardMerchantImportTask importTask = ecardMerchantImportTaskService.selectEcardMerchantImportTaskByTaskId(ecardMerchantInfo.getTaskId());
                    //修改任务为已完成
                    EcardMerchantImportTask ecardMerchantImportTask = new EcardMerchantImportTask();
                    int day = DateUtils.differentDaysByActualMillisecond(importTask.getEndDate(),new Date());
                    if(day > 0){
                        //超时完成
                        ecardMerchantImportTask.setSts("2");
                    }else {
                        //正常完成
                        ecardMerchantImportTask.setSts("1");
                    }
                    //新增建档
                    ecardMerchantImportTask.setSemResult("1");
                    ecardMerchantImportTask.setCloseTime(new Date());
                    ecardMerchantImportTask.setTaskId(ecardMerchantInfo.getTaskId());
                    ecardMerchantImportTaskService.updateEcardMerchantImportTask(ecardMerchantImportTask);

                    if(importTask != null){
                        //修改导入数据状态为建档
                        EcardMerchantImport ecardMerchantImport = new EcardMerchantImport();
                        ecardMerchantImport.setId(importTask.getTaskId());
                        ecardMerchantImport.setWhetherRecord("1");
                        ecardMerchantImportService.updateEcardMerchantImport(ecardMerchantImport);
                    }
                }
            }
            return id > 0 ? ResponseModel.ok(ecardMerchantInfo.getId()) : ResponseModel.error("添加失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-新增建档校验经纬度是否在用户所在的网格区域内接口（公用）
     *
     * @author yuzhiguo
     * @date 2024/11/19 上午8:53
     */
    @PostMapping(value = "/verifyCoordinateInArea")
    @ApiOperation(value = "电子名片-新增建档校验经纬度是否在用户所在的网格区域内接口", notes = "电子名片-新增建档校验经纬度是否在用户所在的网格区域内接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel verifyCoordinateInArea(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);

            JSONObject jsonObject = JSONObject.parseObject(json);
            String coordinate = jsonObject.getString("coordinate");//建档时的经纬度
            if (StringUtils.objIsNullOrEmpty(coordinate)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            //保存时校验传入的经纬度是否在用户所在的网格区域内
            List<JqPoint> ps = new ArrayList<>();//网格范围坐标点集合
            SysDept dept = sysDeptService.selectThirdLevelDeptByDeptId(userInfo.getDeptId());//获取用户所在的支行
            //先根据参数判断是否开启区域限制，0：是，1：否
            String configByKey = sysConfigService.selectConfigByKey("ecard_cross_regional_filing", dept.getDeptId());
            if ("0".equals(configByKey)) {
                String mapGridCoordinate = dept.getMapGridCoordinate();//网格区域坐标点
                if (StringUtils.isNotEmpty(mapGridCoordinate)) {
                    //电子名片存入经纬度是腾讯地图获取的经纬度，由于现在用的是百度地图，所以经纬度需要转换
                    //腾讯经纬度转百度经纬度
                    String clockInPlace[] = coordinate.split(",");
                    String mapTx2bd = JWDUtils.map_tx2bd(Double.valueOf(clockInPlace[0]), Double.valueOf(clockInPlace[1]));
                    log.info("==============建档的坐标点为：" + mapTx2bd);
                    String baiduPlace[] = mapTx2bd.split(",");
                    for (String jwd : mapGridCoordinate.split(";")) {
                        String[] jwdSplit = jwd.split(",");
                        JqPoint jqPoint = new JqPoint(Double.valueOf(jwdSplit[0]), Double.valueOf(jwdSplit[1]));
                        ps.add(jqPoint);
                    }
                    JqPoint n1 = new JqPoint(Double.valueOf(baiduPlace[1]), Double.valueOf(baiduPlace[0]));
                    boolean inPoly = JWDUtils.isPtInPoly(n1.getX(), n1.getY(), ps);
                    if (!inPoly) {
                        return new ResponseModel(ResultStatus.NOT_IN_THE_HOME_GRID.getCode(), "当前位置可能暂未在归属网格范围内，请与管理员联系！");
                    }
                } else {
                    return new ResponseModel(ResultStatus.NOT_IN_THE_HOME_GRID.getCode(), "你所在机构暂未配置网格区域，请与管理员联系！");
                }
            }
            return ResponseModel.ok();
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-调用天眼查接口模糊查询获取工商信息列表
     *
     * @author yuzhiguo
     * @date 2024/11/7 下午1:14
     */
    @PostMapping(value = "/getLikeMerchantByTYC")
    @ApiOperation(value = "电子名片-调用天眼查接口模糊查询获取工商信息列表", notes = "电子名片-调用天眼查接口模糊查询获取工商信息列表")
    @ResponseBody
    @RsaRequest
    public ResponseModel getLikeMerchantByTYC(@RequestBody String json) {
        String salt = getSalt();//盐值
        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        //接口编号
        String apiNum = ecardApiSysConfigService.selectConfigByKey("data.interfaceNum.orgVagueSearch", dept.getDeptId());
        JSONObject jsonObject = JSONObject.parseObject(json);
        String licenseName = jsonObject.getString("licenseName");//营业执照名称
        if (StringUtils.objIsNullOrEmpty(licenseName)) {
            return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
        }
        List<EcardApiMerchantInfo> merchantInfoList = new ArrayList<>();
        /**调用接口*/
        ResponseModel responseModel = ecardOrgInfoApiCommon.getOrgInfoByApi(userInfo, apiNum, licenseName, "");
        if (responseModel.getCode() == 0) {
            JSONObject baseInfo = JSONObject.parseObject(JSON.toJSONString(responseModel.getData()));
            //获取工商数量
            int total = baseInfo.getIntValue("total");
            if (total > 0) {
                /**获取工商信息列表数组*/
                JSONArray items = baseInfo.getJSONArray("items");
                for (int i = 0; i < items.size(); i++) {
                    EcardApiMerchantInfo merchantInfo = new EcardApiMerchantInfo();
                    merchantInfo.setLicenseName(items.getJSONObject(i).getString("name"));//营业执照名称
                    merchantInfo.setCreditCode(items.getJSONObject(i).getString("creditCode"));//统一社会信用编码
                    merchantInfo.setLegalPersonName(items.getJSONObject(i).getString("legalPersonName"));//经营者
                    String time = items.getJSONObject(i).getString("estiblishTime");
                    if (StringUtils.objIsNullOrEmpty(time)){
                        merchantInfo.setEstiblishTime(time);
                    } else {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = null;
                        boolean dateFlag = true;
                        String estiblishTimeStr = "";
                        try {
                            date = sdf.parse(time);
                        } catch (ParseException e) {
                            dateFlag = false;
                        }
                        if (dateFlag) {
                            //日期合法转换，不合法存空
                            estiblishTimeStr = sdf.format(date);
                        }
                        merchantInfo.setEstiblishTime(estiblishTimeStr); //成立日期
                    }
                    merchantInfo.setRegCapital(items.getJSONObject(i).getString("regCapital"));//资金数额
                    merchantInfo.setRegStatus(items.getJSONObject(i).getString("regStatus"));//经营状态
                    merchantInfoList.add(merchantInfo);
                }
            }
        } else {
            return ResponseModel.error(responseModel.getMsg());
        }
        return ResponseModel.okToJSONArray(merchantInfoList);
    }

    /**
     * 电子名片-调用天眼查接口查询获取工商联系方式接口
     *
     * @author yuzhiguo
     * @date 2024/11/7 下午1:34
     */
    @PostMapping(value = "/getMerchantContactByTYC")
    @ApiOperation(value = "电子名片-调用天眼查接口查询获取工商联系方式接口", notes = "电子名片-调用天眼查接口查询获取工商联系方式接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantContactByTYC(@RequestBody String json) {
        String salt = getSalt();//盐值
        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
        SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        //接口编号
        String apiNum = ecardApiSysConfigService.selectConfigByKey("data.interfaceNum.orgContactSearch", dept.getDeptId());
        JSONObject jsonObject = JSONObject.parseObject(json);
        String licenseName = jsonObject.getString("licenseName");//营业执照名称
        if (StringUtils.objIsNullOrEmpty(licenseName)) {
            return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
        }
        List<EcardApiMerchantInfo> merchantInfoList = new ArrayList<>();
        /**调用接口*/
        ResponseModel responseModel = ecardOrgInfoApiCommon.getOrgInfoByApi(userInfo, apiNum, licenseName, "");
        if (responseModel.getCode() == 0) {
            JSONObject baseInfo = JSONObject.parseObject(JSON.toJSONString(responseModel.getData()));
            EcardApiMerchantInfo merchantInfo = new EcardApiMerchantInfo();
            merchantInfo.setPhoneNumber(baseInfo.getString("phoneNumber"));//联系方式
            merchantInfoList.add(merchantInfo);
        } else {
            return ResponseModel.error(responseModel.getMsg());
        }
        return ResponseModel.okToJSONArray(merchantInfoList);
    }

    /**
     * 电子名片-查询个人/商户/企业/新型农业主体成员列表接口（公用）
     *
     * @param: merchantId 商户ID
     * @author yjs
     * @date 2023/7/26 10:08
     */
    @PostMapping(value = "/getMerchantPartList")
    @ApiOperation(value = "电子名片-查询个人/商户/企业/新型农业主体成员列表接口", notes = "电子名片-查询个人/商户/企业/新型农业主体成员列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantPartList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());

            JSONObject jsonObject = JSONObject.parseObject(json);
            Long merchantId = jsonObject.getLong("merchantId");
            String merchantType = jsonObject.getString("merchantType");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            if (StringUtils.objIsNullOrEmpty(merchantId) || StringUtils.objIsNullOrEmpty(merchantType)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            List<EcardApiMerchantPartInfo> ecardMerchantPartInfos = ecardMerchantPartInfoService.getMerchantPartList(merchantId, merchantType, wechatApplet.getDeptId(), salt);
            return ResponseModel.okToJSONArray(ecardMerchantPartInfos);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询个人/商户/企业/新型农业主体成员详情接口，客户经理只能查看自己商户的成员信息（公用）
     *
     * @author yjs
     * @date 2023/7/26 10:33
     */
    @PostMapping("/getMerchantPartInfo")
    @ApiOperation(value = "电子名片-查询个人/商户/企业/新型农业主体成员详情接口", notes = "电子名片-查询个人/商户/企业/新型农业主体成员详情接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantPartInfo(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiEcardRegistInfo ecardApiEcardRegistInfo = registInfoService.selectEcardApiEcardRegistInfoByRegistId(Long.valueOf(currentUserId), salt);

            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");

            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            if (ecardApiEcardRegistInfo != null && !StringUtils.objIsNullOrEmpty(ecardApiEcardRegistInfo.getRegistId())) {
                EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
                if (roles.equals(ecardApiEcardRegistInfo.getRoles())) {
                    EcardApiMerchantPartInfo merchantPartInfo = ecardMerchantPartInfoService.selectEcardMerchantPartInfoById(id, salt);
                    return ResponseModel.okToJSON(merchantPartInfo);
                } else {
                    return ResponseModel.error("您没有查看该商户成员的权限！");
                }

            } else {
                return ResponseModel.error("用户信息不存在！");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-保存商户成员数据接口（公用）
     * 注：个人/商户/企业/新型农业主成员信息保存调用的保存个人/商户/企业/新型农业主信息接口
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/addMerchantPartInfo")
    @ApiOperation(value = "电子名片-保存个人/商户/企业/新型农业主体成员数据接口", notes = "电子名片-保存商户/企业/新型农业主体成员数据接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel addMerchantPartInfo(@RequestBody EcardApiMerchantPartInfo ecardMerchantPartInfo) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiEcardRegistInfo ecardApiEcardRegistInfo = registInfoService.selectEcardApiEcardRegistInfoByRegistId(Long.valueOf(currentUserId), salt);
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            if (!roles.equals(ecardApiEcardRegistInfo.getRoles())) {
                return ResponseModel.error("您没有编辑该成员的权限！");
            }
            String merchantType = ecardMerchantPartInfo.getMerchantType();//商户类型：1-个人，2-商户，3-企业，4-新型农业主体

            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());

            if (!StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getIdCard())) {
                EcardApiMerchantPartInfo merchantPartInfo = new EcardApiMerchantPartInfo();
                merchantPartInfo.setMerchantId(ecardMerchantPartInfo.getMerchantId());
                merchantPartInfo.setIdCard(ecardMerchantPartInfo.getIdCard());
                merchantPartInfo.setMerchantType(merchantType);//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
                List<EcardApiMerchantPartInfo> partInfoList = ecardMerchantPartInfoService.selectEcardMerchantPartInfoList(merchantPartInfo, salt);
                if (partInfoList != null && partInfoList.size() > 0) {
                    //判断是新增还是编辑
                    if (StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getId())) {
                        return ResponseModel.error("员工信息已存在！");
                    }else{
                        if (!partInfoList.get(0).getId().equals(ecardMerchantPartInfo.getId())){
                            return ResponseModel.error("员工信息已存在！");
                        }
                    }
                }
            }

            //商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            if ("2".equals(merchantType)){//商户
                //校验商户是否属于当前登录人
                EcardApiMerchantInfo ecardApiMerchantInfo = ecardMerchantInfoService.selectEcardMerchantInfoById(ecardMerchantPartInfo.getMerchantId(), salt);
                if (ecardApiMerchantInfo == null) {
                    return ResponseModel.error("商户信息不存在，请核实！");
                } else {
                    if (ecardApiMerchantInfo.getCreatorId().longValue() != ecardApiEcardRegistInfo.getRegistId().longValue()) {
                        return ResponseModel.error("您没有编辑该商户成员的权限！");
                    }
                }
            }
            //查询商户人员是否存在
            if (!StringUtils.objIsNullOrEmpty(ecardMerchantPartInfo.getId())) {
                EcardApiMerchantPartInfo ecardApiMerchantPartInfo = ecardMerchantPartInfoService.selectEcardMerchantPartInfoById(ecardMerchantPartInfo.getId(), salt);
                if (ecardApiMerchantPartInfo == null) {
                    //移交商户时没有修改商户成员创建人，这里不在校验商户成员创建人
                    /*if (ecardApiMerchantPartInfo.getCreatorId().longValue() != ecardApiEcardRegistInfo.getRegistId().longValue()) {
                        return ResponseModel.error("您没有编辑该商户成员的权限！");
                    }*/
                    return ResponseModel.error("成员信息不存在，请核实！");
                }
            }

            //当前登录人Id
            ecardMerchantPartInfo.setCreatorId(Long.valueOf(currentUserId));

            //添加时根据商户id和商户类型判断有没有成员，没有把是否联系人字段改为是，有不操作
            List<EcardApiMerchantPartInfo> ecardMerchantPartInfos = ecardMerchantPartInfoService.getMerchantPartList(ecardMerchantPartInfo.getMerchantId(), merchantType, wechatApplet.getDeptId(), salt);
            if (ecardMerchantPartInfos.size() == 0){
                ecardMerchantPartInfo.setIsContacts("T");
            }
            int updateCount = ecardMerchantPartInfoService.addMerchantPartInfo(ecardMerchantPartInfo, salt);
            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("添加失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-删除个人/商户/企业/新型农业主体成员成员接口（公用）
     *
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/delectMerchant")
    @ApiOperation(value = "电子名片-删除个人/商户/企业/新型农业主体成员接口", notes = "电子名片-删除个人/商户/企业/新型农业主体成员接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel delectMerchant(@RequestBody String json) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            int delectCount = ecardMerchantPartInfoService.deleteEcardMerchantPartInfoById(id);
            return delectCount > 0 ? ResponseModel.ok() : ResponseModel.error("删除失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-修改个人/商户/企业/新型农业主体成员联系人接口（公用）
     *
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/modifyMerchantContacts")
    @ApiOperation(value = "电子名片-修改个人/商户/企业/新型农业主体成员联系人接口", notes = "电子名片-修改个人/商户/企业/新型农业主体成员联系人接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel modifyMerchantContacts(@RequestBody String json) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            Long merchantId = jsonObject.getLong("merchantId");
            String merchantType = jsonObject.getString("merchantType");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            if (StringUtils.objIsNullOrEmpty(id) || StringUtils.objIsNullOrEmpty(merchantId) || StringUtils.objIsNullOrEmpty(merchantType)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            int updateCount = ecardMerchantPartInfoService.modifyMerchantContacts(id, merchantId, merchantType);
            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("修改失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询个人/商户/企业/新型农业主体拜访记录列表接口（公用）
     *
     * @author yjs
     * @date 2023/7/26 9:08
     */
    @PostMapping(value = "/getMerchantVisitList")
    @ApiOperation(value = "电子名片-查询个人/商户/企业/新型农业主体拜访记录列表接口", notes = "电子名片-查询个人/商户/企业/新型农业主体拜访记录列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantVisitList(@RequestBody String json) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long merchantId = jsonObject.getLong("merchantId");
            String merchantType = jsonObject.getString("merchantType");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            if (StringUtils.objIsNullOrEmpty(merchantId)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardApiMerchantVisitInfo merchantVisitInfo = new EcardApiMerchantVisitInfo();
            merchantVisitInfo.setMerchantId(merchantId);
            merchantVisitInfo.setMerchantType(merchantType);//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            List<EcardApiMerchantVisitInfo> visitInfoList = ecardMerchantVisitInfoService.getMerchantVisitList(merchantVisitInfo);
            return ResponseModel.okToJSONArray(visitInfoList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询个人/商户/企业/新型农业主体拜访记录详情接口（公用）
     *
     * @author yjs
     * @date 2023/7/26 9:08
     */
    @PostMapping(value = "/getMerchantVisitInfo")
    @ApiOperation(value = "电子名片-查询个人/商户/企业/新型农业主体拜访记录详情接口", notes = "电子名片-查询个人/商户/企业/新型农业主体拜访记录详情接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantVisitInfo(@RequestBody String json) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardApiMerchantVisitInfo merchantVisitInfo = ecardMerchantVisitInfoService.selectEcardMerchantVisitInfoById(id);
            return ResponseModel.okToJSON(merchantVisitInfo);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-保存个人/商户/企业/新型农业主体拜访记录接口（公用）
     *
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/addMerchantVisitInfo")
    @ApiOperation(value = "电子名片-保存个人/商户/企业/新型农业主体拜访记录接口", notes = "电子名片-保存个人/商户/企业/新型农业主体拜访记录接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel addMerchantVisitInfo(@RequestBody EcardApiMerchantVisitInfo ecardMerchantVisitInfo) {
        try {
            String currentUserId = getCurrentUserId();
            //当前登录人Id
            ecardMerchantVisitInfo.setCreatorId(Long.valueOf(currentUserId));
            int updateCount = ecardMerchantVisitInfoService.insertEcardMerchantVisitInfo(ecardMerchantVisitInfo);

            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("添加失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-新增拜访校验经纬度是否在配置的范围内接口（公用）
     *
     * @author yuzhiguo
     * @date 2024/11/19 上午9:10
     */
    @PostMapping(value = "/verifyVisitInArea")
    @ApiOperation(value = "电子名片-新增拜访校验经纬度是否在配置的范围内接口", notes = "电子名片-新增拜访校验经纬度是否在配置的范围内接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel verifyVisitInArea(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            JSONObject jsonObject = JSONObject.parseObject(json);
            String merchantType = jsonObject.getString("merchantType");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            Long merchantId = jsonObject.getLong("merchantId");//商户id
            String coordinate = jsonObject.getString("coordinate");//拜访时的经纬度
            if (StringUtils.objIsNullOrEmpty(merchantType) || StringUtils.objIsNullOrEmpty(merchantId)
                    || StringUtils.objIsNullOrEmpty(coordinate)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //校验拜访是否在配置的范围内
            //商户建档的经纬度
            String clockInPlace[] = new String[0];
            if ("1".equals(merchantType)){//1-个人
                EcardApiPersonInfo personInfo = ecardPersonInfoService.selectEcardPersonInfoById(merchantId, salt);
                clockInPlace = personInfo.getManageCoordinate().split(",");
            } else if ("2".equals(merchantType)){//2-商户
                EcardApiMerchantInfo merchantInfo = ecardMerchantInfoService.selectEcardMerchantInfoById(merchantId, salt);
                clockInPlace = merchantInfo.getCoordinate().split(",");
            } else if ("3".equals(merchantType)){//3-企业
                EcardApiEnterpriseInfo enterpriseInfo = ecardEnterpriseInfoService.selectEcardEnterpriseInfoById(merchantId, salt);
                clockInPlace = enterpriseInfo.getEntCoordinate().split(",");
            } else if ("4".equals(merchantType)){//4-新型农业主体
                EcardApiAgricultureInfo agricultureInfo = ecardAgricultureInfoService.selectEcardAgricultureInfoById(merchantId, salt);
                clockInPlace = agricultureInfo.getAgrCoordinate().split(",");
            }

            //拜访时传的经纬度
            String place[] = coordinate.split(",");
            //计算距离
            Double distance = GeoUtil.GetDistance(Double.valueOf(clockInPlace[1]), Double.valueOf(clockInPlace[0]), Double.valueOf(place[1]), Double.valueOf(place[0]));
            String configKey = "";
            String tips = "";
            switch (merchantType) {
                case "1": //个人
                    //替换对应参数键值
                    configKey = "ecard_person_visit_distance_limit";
                    tips = "个人";
                    break;
                case "2": //商户
                    configKey = "ecard_merchant_visit_distance_limit";
                    tips = "商户";
                    break;
                case "3": //企业
                    configKey = "ecard_enterprise_visit_distance_limit";
                    tips = "企业";
                    break;
                case "4": //新型农业主体
                    configKey = "ecard_agriculture_visit_distance_limit";
                    tips = "新型农业主体";
                    break;
            }
            //查询系统参数配置的范围
            SysConfig config = new SysConfig();
            config.setConfigKey(configKey);
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            config.setDeptId(sysDept.getDeptId());
            SysConfig sysConfig = ecardApiSysConfigService.selectConfig(config);

            BigDecimal bigDistance = new BigDecimal(distance);
            BigDecimal bigValue = new BigDecimal(sysConfig.getConfigValue());
            log.info("拜访时的坐标和" + tips + "之间的距离为========================= " + bigDistance);
            if (bigDistance.compareTo(bigValue) > 0) {
                return new ResponseModel(ResultStatus.NOT_IN_THE_HOME_GRID.getCode(), "您所在位置不在该" + tips + "位置范围内！");
            } else {
                return ResponseModel.ok();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-保存个人/商户/企业/新型农业主体转交记录接口（公用）
     *
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/addMerchantTransferInfo")
    @ApiOperation(value = "电子名片-保存个人/商户/企业/新型农业主体转交记录接口", notes = "电子名片-保存个人/商户/企业/新型农业主体转交记录接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel addMerchantTransferInfo(@RequestBody EcardApiMerchantHandover ecardMerchantHandover) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前登录人userId
            ecardMerchantHandover.setTransferId(Long.valueOf(currentUserId));
            ecardMerchantHandover.setTransferDeptId(userInfo.getDeptId());
            int updateCount = ecardMerchantInfoService.addMerchantTransferInfo(ecardMerchantHandover);
            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("转交失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-根据ID修改商户状态（单用）
     *
     * @author yjs
     * @date 2023/7/26 10:48
     */
    @PostMapping(value = "/changeMerchantStatus")
    @ApiOperation(value = "电子名片-根据ID修改商户状态", notes = "电子名片-根据ID修改商户状态")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel changeMerchantStatus(@RequestBody String json) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            int updateCount = ecardMerchantInfoService.changeMerchantStatus(id);
            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("删除失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-商户营销任务列表接口（公用）
     *
     * @author yjs
     * @date 2023/7/31 14:08
     */
    @PostMapping(value = "/getMerchantTaskList")
    @ApiOperation(value = "电子名片-商户营销任务列表接口", notes = "电子名片-商户营销任务列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            String orderByStr = jsonObject.getString("orderBy");
            String merchantType = jsonObject.getString("merchantType");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            String search = jsonObject.getString("search");//查询条件姓名和手机号拆开
            String phone = jsonObject.getString("phone");//手机号
            String orderBy = SqlUtil.escapeOrderBySql(orderByStr);
            PageHelper.startPage(pageNum, pageSize, orderBy);
            List<EcardApiMerchantTask> merchantTaskList = ecardApiMerchantTaskService.getMerchantTaskList(Long.valueOf(currentUserId), merchantType, search, wechatApplet.getDeptId(), phone, salt);//字典机构查询条件
            return ResponseModel.okToJSONArray(new PageInfo(merchantTaskList).getTotal(), merchantTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /**
     * 电子名片-查询个人/商户/企业/新型农业主体网格任务总条数接口（公用）
     *
     * @author yuzhiguo
     * @date 2024/7/15 上午9:56
     */
    @PassToken
    @PostMapping(value = "/getMerchantTaskTotalNum")
    @ApiOperation(value = "电子名片-查询个人/商户/企业/新型农业主体网格任务总条数接口", notes = "电子名片-查询个人/商户/企业/新型农业主体网格任务总条数接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantTaskTotalNum() {
        try {
            String currentUserId = getCurrentUserId();
            int taskTotalNum = 0;
            if (!StringUtil.objIsNullOrEmpty(currentUserId)) {
                taskTotalNum = ecardMerchantInfoService.getMerchantTaskTotalNum(Long.valueOf(currentUserId));
            }
            return ResponseModel.ok(taskTotalNum);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /***
     * 电子名片-商户预约任务列表接口（公用）
     * @param json
     * @return: com.xydtech.common.model.ResponseModel
     * @Author: lin
     * @Date: 2023/8/7 15:47
     */
    @PostMapping(value = "/getMerchantReservationTaskList")
    @ApiOperation(value = "电子名片-商户预约任务列表接口", notes = "电子名片-商户预约任务列表接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantReservationTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            String currentUserId = getCurrentUserId();
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);
            //当前小程序id
            SysWechatApplet wechatApplet = getAppIdByDeptId(userInfo.getDeptId());
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            String orderByStr = jsonObject.getString("orderBy");
            String merchantType = jsonObject.getString("merchantType");//商户类型：1-个人，2-商户，3-企业，4-新型农业主体
            String search = jsonObject.getString("search");//查询条件姓名和手机号拆开
            String phone = jsonObject.getString("phone");
            String orderBy = SqlUtil.escapeOrderBySql(orderByStr);
            PageHelper.startPage(pageNum, pageSize, orderBy);
            List<EcardApiMerchantReservationTask> merchantReservationTaskList = ecardApiMerchantReservationTaskService.getMerchantReservationTaskList(Long.valueOf(currentUserId), merchantType, search, wechatApplet.getDeptId(), phone, salt);
            return ResponseModel.okToJSONArray(new PageInfo(merchantReservationTaskList).getTotal(), merchantReservationTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /***
     * 电子名片-修改个人/商户/企业/新型农业主体预约任务接口（公用）
     * @param ecardApiMerchantReservationTask
     * @return: com.xydtech.common.model.ResponseModel
     * @Author: lin
     * @Date: 2023/8/7 15:47
     */
    @PostMapping(value = "/changeMerchantReservationTask")
    @ApiOperation(value = "电子名片-修改个人/商户/企业/新型农业主体预约任务接口", notes = "电子名片-修改个人/商户/企业/新型农业主体预约任务接口")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel changeMerchantReservationTask(@RequestBody EcardApiMerchantReservationTask ecardApiMerchantReservationTask) {
        try {
            String currentUserId = getCurrentUserId();
            EcardApiMerchantReservationTask oldEcardApiMerchantReservationTask = ecardApiMerchantReservationTaskService.selectEcardMerchantReservationTaskById(ecardApiMerchantReservationTask.getId());
            //计算是否超时完成
            Date today = DateUtils.parseDate(DateUtils.getDate());
            int i = DateUtils.differentsecond(oldEcardApiMerchantReservationTask.getAppointmentDate(), today);
            if (i >= 0) {
                ecardApiMerchantReservationTask.setTaskSts("1");
            } else {
                //超时完成
                ecardApiMerchantReservationTask.setTaskSts("2");
            }
            //当前登录人Id
            ecardApiMerchantReservationTask.setCmRegistId(Long.valueOf(currentUserId));
            ecardApiMerchantReservationTask.setFinishTime(new Date());

            int updateCount = ecardApiMerchantReservationTaskService.updateEcardMerchantReservationTask(ecardApiMerchantReservationTask);
            return updateCount > 0 ? ResponseModel.ok() : ResponseModel.error("处理失败！");
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /***
     * 电子名片-查询个人/商户/企业/新型农业主体预约任务详情接口（公用）
     * @param json
     * @return: com.xydtech.common.model.ResponseModel
     * @Author: lin
     * @Date: 2023/8/7 15:47
     */
    @PostMapping(value = "/getMerchantReservationTaskInfo")
    @ApiOperation(value = "电子名片-查询个人/商户/企业/新型农业主体预约任务详情接口", notes = "电子名片-查询个人/商户/企业/新型农业主体预约任务详情接口")
    @ResponseBody
    @RsaRequest
    public ResponseModel getMerchantReservationTaskInfo(@RequestBody String json) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            Long id = jsonObject.getLong("id");
            if (StringUtils.objIsNullOrEmpty(id)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardApiMerchantReservationTask merchantReservationTask = ecardApiMerchantReservationTaskService.selectEcardMerchantReservationTaskById(id);
            return ResponseModel.okToJSON(merchantReservationTask);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败，请联系管理员！");
        }
    }

    /***
     *  计算选择区域是否在配置的范围内（公用）
     *  coordinate        定位经纬度
     *  chooseCoordinate  选择的经纬度
     * @return: com.xydtech.common.model.ResponseModel
     * @Author: lin
     * @Date: 2023/8/7 16:30
     */
    @PostMapping(value = "/calculateDistance")
    @ApiOperation(value = "电子名片-计算距离定位中心的距离是否在配置区域内", notes = "电子名片-计算距离定位中心的距离是否在配置区域内")
    @ResponseBody
    @RsaRequest(result = false)
    public ResponseModel calculateDistance(@RequestBody String json) {
        String salt = getSalt();//盐值
        JSONObject jsonObject = JSONObject.parseObject(json);
        String coordinate = jsonObject.getString("coordinate");
        String chooseCoordinate = jsonObject.getString("chooseCoordinate");
        if (StringUtils.objIsNullOrEmpty(coordinate) || StringUtils.objIsNullOrEmpty(chooseCoordinate)) {
            return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
        }

        String currentUserId = getCurrentUserId();
        EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(currentUserId, salt);

        //选择的经纬度
        String clockInPlace[] = chooseCoordinate.split(",");
        //定位的商户经纬度
        String place[] = coordinate.split(",");
        Double distance = GeoUtil.GetDistance(Double.valueOf(clockInPlace[1]), Double.valueOf(clockInPlace[0]), Double.valueOf(place[1]), Double.valueOf(place[0]));

        SysConfig config = new SysConfig();
        config.setConfigKey("ecard_merchant_position_distance");
        SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
        config.setDeptId(sysDept.getDeptId());
        SysConfig sysConfig = ecardApiSysConfigService.selectConfig(config);

        BigDecimal bigDistance = new BigDecimal(distance);
        BigDecimal bigValue = new BigDecimal(sysConfig.getConfigValue());

        if (bigDistance.compareTo(bigValue) > 0) {
            return ResponseModel.error("所选位置超出系统配置的距离，请重新选择！");
        } else {
            return ResponseModel.ok();
        }

    }

//-----------------------------------------------------------------以下为统计接口--------------------------------------------------------------------

    /**
     * 电子名片-我的建档拜访数量统计接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午9:08
     */
    @PostMapping(value = "/getFilingVisitsStatistics")
    @ApiOperation(value = "电子名片-我的建档拜访数量统计接口", notes = "电子名片-我的建档拜访数量统计接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getFilingVisitsStatistics() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardBranchEcardChartService.getFilingVisitsStatistics(userInfo.getUserId());
            EcardBranchEcardChart ecardChart = new EcardBranchEcardChart();
            ecardChart.setMerchantNum(jsonObject.getLong("perFilingNums"));//建档总数
            ecardChart.setVisitSum(jsonObject.getLong("perVisitNums"));//拜访总数
            ecardChart.setDoTaskSum(jsonObject.getLong("perDoVisitNums"));//超时拜访
            ecardChart.setUndoTaskSum(jsonObject.getLong("perUnDoVisitNums"));//超时未拜访
            ecardChart.setMerchantMonthNum(jsonObject.getLong("perFilingThisMonthNums"));//本月新增商户数
            ecardChart.setMerchantLastMonthNum(jsonObject.getLong("perFilingCompareNums"));//商户较上月增加数
            ecardChart.setVisitMouthSum(jsonObject.getLong("perVisitThisMonthNums"));//本月新增拜访数
            ecardChart.setVisitLastMouthNum(jsonObject.getLong("perVisitCompareNums"));//拜访较上月增加数
            if (ecardChart.getMerchantLastMonthNum() >= 0){
                ecardChart.setCompareMerchantType("1");//较上月商户类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareMerchantType("2");//较上月商户类型（1：上升，2：下降）
            }
            if (ecardChart.getVisitLastMouthNum() >= 0){
                ecardChart.setCompareVisitType("1");//较上月拜访类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareVisitType("2");//较上月拜访类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(ecardChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-全行建档拜访数量统计接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午9:08
     */
    @PostMapping(value = "/getAllFilingVisitsNums")
    @ApiOperation(value = "电子名片-全行建档拜访数量统计接口", notes = "电子名片-全行建档拜访数量统计接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getAllFilingVisitsNums() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardBranchEcardChartService.getAllFilingVisitsNums(userInfo.getDeptId());
            EcardBranchEcardChart ecardChart = new EcardBranchEcardChart();
            ecardChart.setMerchantNum(jsonObject.getLong("filingNums"));//全行建档总数
            ecardChart.setFilingLastMonthNums(jsonObject.getLong("filingLastMonthNums"));//上月新增建档总数
            ecardChart.setMerchantMonthNum(jsonObject.getLong("filingThisMonthNums"));//本月新增建档总数
            ecardChart.setMerchantLastMonthNum(jsonObject.getLong("filingCompareNums"));//建档较上月对比
            ecardChart.setVisitSum(jsonObject.getLong("visitNums"));//拜访总次数
            ecardChart.setVisitNewLastMonthNums(jsonObject.getLong("visitLastMonthNums"));//上月新增拜访总数
            ecardChart.setVisitMouthSum(jsonObject.getLong("visitThisMonthNums"));//本月新增拜访总数
            ecardChart.setVisitLastMouthNum(jsonObject.getLong("visitCompareNums"));//拜访较上月对比
            if (ecardChart.getMerchantLastMonthNum() >= 0){
                ecardChart.setCompareMerchantType("1");//较上月建档类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareMerchantType("2");//较上月建档类型（1：上升，2：下降）
            }
            if (ecardChart.getVisitLastMouthNum() >= 0){
                ecardChart.setCompareVisitType("1");//较上月拜访类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareVisitType("2");//较上月拜访类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(ecardChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-超时拜访数量统计接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午9:08
     */
    @PostMapping(value = "/getTimeoutVisitsNums")
    @ApiOperation(value = "电子名片-超时拜访数量统计接口", notes = "电子名片-超时拜访数量统计接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getTimeoutVisitsNums() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = ecardBranchEcardChartService.getTimeoutVisitsNums(userInfo.getDeptId());
            EcardBranchEcardChart ecardChart = new EcardBranchEcardChart();
            ecardChart.setDoTaskSum(jsonObject.getLong("doTaskNums"));//超时拜访总数
            ecardChart.setDoTaskLastMonthNums(jsonObject.getLong("doTaskLastMonthNums"));//上月新增超时拜访总数
            ecardChart.setDoTaskThisMonthNums(jsonObject.getLong("doTaskThisMonthNums"));//本月新增超时拜访总数
            ecardChart.setDoTaskCompareNums(jsonObject.getLong("doTaskCompareNums"));//超时拜访较上月对比
            ecardChart.setUndoTaskSum(jsonObject.getLong("undoTaskNums"));//超时未拜访总次数
            ecardChart.setUndoTaskLastMonthNums(jsonObject.getLong("undoTaskLastMonthNums"));//上月新增超时未拜访总数
            ecardChart.setUndoTaskThisMonthNums(jsonObject.getLong("undoTaskThisMonthNums"));//本月新增超时未拜访总数
            ecardChart.setUndoTaskCompareNums(jsonObject.getLong("undoTaskCompareNums"));//超时未拜访较上月对比
            if (ecardChart.getDoTaskCompareNums() >= 0){
                ecardChart.setCompareDoType("1");//较上月超时拜访类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareDoType("2");//较上月超时拜访类型（1：上升，2：下降）
            }
            if (ecardChart.getUndoTaskCompareNums() >= 0){
                ecardChart.setCompareUndoType("1");//较上月超时未拜访类型（1：上升，2：下降）
            } else {
                ecardChart.setCompareUndoType("2");//较上月超时未拜访类型（1：上升，2：下降）
            }
            return ResponseModel.okToJSON(ecardChart);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-查询建档折线图数据接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午9:16
     */
    @PostMapping(value = "/getFilingLineChart")
    @ApiOperation(value = "电子名片-查询建档折线图数据接口", notes = "电子名片-查询建档折线图数据接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getFilingLineChart() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            List<EcardBranchEcardChart> ecardBranchEcardChartList = ecardBranchEcardChartService.getFilingLineChartByApplet(userInfo.getDeptId());
            return ResponseModel.okToJSONArray(ecardBranchEcardChartList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-查询拜访柱状图数据接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午10:25
     */
    @PostMapping(value = "/getVisitLineChart")
    @ApiOperation(value = "电子名片-查询拜访柱状图数据接口", notes = "电子名片-查询拜访柱状图数据接口")
    @ResponseBody
    @RsaRequest(param = false)
    public ResponseModel getVisitLineChart() {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            List<EcardBranchEcardChart> ecardBranchEcardChartList = ecardBranchEcardChartService.getVisitLineChartByApplet(userInfo.getDeptId());
            return ResponseModel.okToJSONArray(ecardBranchEcardChartList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-各机构商户建档排名接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午10:40
     */
    @PostMapping(value = "/getDeptFilingList")
    @ApiOperation(value = "电子名片-各机构商户建档排名", notes = "电子名片-各机构商户建档排名")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getDeptFilingList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchDeptFiling ecardBranchDeptFiling = new EcardBranchDeptFiling();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchDeptFiling.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchDeptFiling.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchDeptFiling> ecardBranchDeptFilingList = ecardBranchEcardChartService.getDeptFilingListByApplet(ecardBranchDeptFiling);
            for (EcardBranchDeptFiling branchDeptFiling : ecardBranchDeptFilingList) {
                if (branchDeptFiling.getMerchantCompareNum() >= 0){
                    branchDeptFiling.setCompareType("1");//较上月类型（1：上升，2：下降）
                } else {
                    branchDeptFiling.setCompareType("2");//较上月类型（1：上升，2：下降）
                }
            }
            PageInfo pageInfo = new PageInfo(ecardBranchDeptFilingList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchDeptFilingList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-营销人员商户建档排名接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午11:10
     */
    @PostMapping(value = "/getUserFilingList")
    @ApiOperation(value = "电子名片-营销人员商户建档排名接口", notes = "电子名片-营销人员商户建档排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getUserFilingList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            Long appQueryDeptId = jsonObject.getLong("appQueryDeptId");//小程序传参查询用的deptId
            String userName = jsonObject.getString("userName");//小程序传参查询用的营销人员姓名
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchUserFiling ecardBranchUserFiling = new EcardBranchUserFiling();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchUserFiling.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchUserFiling.setDeptId(sysDept.getDeptId());
            ecardBranchUserFiling.setAppQueryDeptId(appQueryDeptId);
            ecardBranchUserFiling.setUserName(userName);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchUserFiling> ecardBranchUserFilingList = ecardBranchEcardChartService.getUserFilingListByApplet(ecardBranchUserFiling);
            PageInfo pageInfo = new PageInfo(ecardBranchUserFilingList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchUserFilingList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-机构拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午11:24
     */
    @PostMapping(value = "/getDeptVisitsList")
    @ApiOperation(value = "电子名片-机构拜访次数排名接口", notes = "电子名片-机构拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getDeptVisitsList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchDeptVisit ecardBranchDeptVisit = new EcardBranchDeptVisit();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchDeptVisit.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchDeptVisit.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchDeptVisit> ecardBranchDeptVisitList = ecardBranchEcardChartService.getDeptVisitsListByApplet(ecardBranchDeptVisit);
            for (EcardBranchDeptVisit branchDeptVisit : ecardBranchDeptVisitList) {
                if (branchDeptVisit.getVisitCompareNum() >= 0){
                    branchDeptVisit.setCompareType("1");//较上月类型（1：上升，2：下降）
                } else {
                    branchDeptVisit.setCompareType("2");//较上月类型（1：上升，2：下降）
                }
            }
            PageInfo pageInfo = new PageInfo(ecardBranchDeptVisitList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchDeptVisitList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-营销人员拜访次数排名
     *
     * @author yuzhiguo
     * @date 2024/6/6 上午11:30
     */
    @PostMapping(value = "/getUserVisitsList")
    @ApiOperation(value = "电子名片-营销人员拜访次数排名", notes = "电子名片-营销人员拜访次数排名")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getUserVisitsList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            Long appQueryDeptId = jsonObject.getLong("appQueryDeptId");//小程序传参查询用的deptId
            String userName = jsonObject.getString("userName");//小程序传参查询用的营销人员姓名
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchUserVisit ecardBranchUserVisit = new EcardBranchUserVisit();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchUserVisit.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchUserVisit.setDeptId(sysDept.getDeptId());
            ecardBranchUserVisit.setAppQueryDeptId(appQueryDeptId);
            ecardBranchUserVisit.setUserName(userName);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchUserVisit> ecardBranchUserVisitList = ecardBranchEcardChartService.getUserVisitsListByApplet(ecardBranchUserVisit);
            PageInfo pageInfo = new PageInfo(ecardBranchUserVisitList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchUserVisitList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-机构超时拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 下午1:08
     */
    @PostMapping(value = "/getDeptDoTaskList")
    @ApiOperation(value = "电子名片-机构超时拜访次数排名接口", notes = "电子名片-机构超时拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getDeptDoTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchDeptDoTask ecardBranchDeptDoTask = new EcardBranchDeptDoTask();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchDeptDoTask.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchDeptDoTask.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchDeptDoTask> ecardBranchDeptDoTaskList = ecardBranchEcardChartService.getDeptDoTaskListByApplet(ecardBranchDeptDoTask);
            PageInfo pageInfo = new PageInfo(ecardBranchDeptDoTaskList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchDeptDoTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-机构超时未拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 下午1:20
     */
    @PostMapping(value = "/getDeptUnDoTaskList")
    @ApiOperation(value = "电子名片-机构超时未拜访次数排名接口", notes = "电子名片-机构超时未拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getDeptUnDoTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchDeptUndoTask ecardBranchDeptUndoTask = new EcardBranchDeptUndoTask();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchDeptUndoTask.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchDeptUndoTask.setDeptId(sysDept.getDeptId());
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchDeptUndoTask> ecardBranchDeptUndoTaskList = ecardBranchEcardChartService.getDeptUnDoTaskListByApplet(ecardBranchDeptUndoTask);
            PageInfo pageInfo = new PageInfo(ecardBranchDeptUndoTaskList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchDeptUndoTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-营销人员超时拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 下午2:10
     */
    @PostMapping(value = "/getUserDoTaskList")
    @ApiOperation(value = "电子名片-营销人员超时拜访次数排名接口", notes = "电子名片-营销人员超时拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getUserDoTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            Long appQueryDeptId = jsonObject.getLong("appQueryDeptId");//小程序传参查询用的deptId
            String userName = jsonObject.getString("userName");//小程序传参查询用的营销人员姓名
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchUserDoTask ecardBranchUserDoTask = new EcardBranchUserDoTask();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchUserDoTask.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchUserDoTask.setDeptId(sysDept.getDeptId());
            ecardBranchUserDoTask.setAppQueryDeptId(appQueryDeptId);
            ecardBranchUserDoTask.setUserName(userName);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchUserDoTask> ecardBranchUserDoTaskList = ecardBranchEcardChartService.getUserDoTaskListByApplet(ecardBranchUserDoTask);
            PageInfo pageInfo = new PageInfo(ecardBranchUserDoTaskList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchUserDoTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }

    /**
     * 电子名片-营销人员超时未拜访次数排名接口
     *
     * @author yuzhiguo
     * @date 2024/6/6 下午3:24
     */
    @PostMapping(value = "/getUserUnDoTaskList")
    @ApiOperation(value = "电子名片-营销人员超时未拜访次数排名接口", notes = "电子名片-营销人员超时未拜访次数排名接口")
    @ResponseBody
    @RsaRequest(param = true, result = true)
    public ResponseModel getUserUnDoTaskList(@RequestBody String json) {
        try {
            String salt = getSalt();//盐值
            //获取当前用户的信息
            EcardApiUserInfo userInfo = ecardApiUserService.getUserInfo(getCurrentUserId(), salt);
            JSONObject jsonObject = JSONObject.parseObject(json);
            int pageNum = jsonObject.getInteger("pageNum");
            int pageSize = jsonObject.getInteger("pageSize");
            Long appQueryDeptId = jsonObject.getLong("appQueryDeptId");//小程序传参查询用的deptId
            String userName = jsonObject.getString("userName");//小程序传参查询用的营销人员姓名
            if (StringUtils.objIsNullOrEmpty(pageNum) || StringUtils.objIsNullOrEmpty(pageSize)) {
                return ResponseModel.error(ResultStatus.PARAMETER_MISSING);
            }
            EcardBranchUserUndoTask ecardBranchUserUndoTask = new EcardBranchUserUndoTask();
            SysDept dept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());
            //是否只查业务条线（支行和分理处，不含总行各部室），0：是，1：否
            String ecardMerchantIsdept = sysConfigService.selectConfigByKey("ecard_merchant_isdept", dept.getDeptId());
            if ("0".equals(ecardMerchantIsdept)){
                ecardBranchUserUndoTask.setIsServiceLine(ecardMerchantIsdept);//是
            }
            SysDept sysDept = sysDeptService.selectSecondLevelDeptByDeptId(userInfo.getDeptId());//获取县级机构
            ecardBranchUserUndoTask.setDeptId(sysDept.getDeptId());
            ecardBranchUserUndoTask.setAppQueryDeptId(appQueryDeptId);
            ecardBranchUserUndoTask.setUserName(userName);
            PageHelper.startPage(pageNum, pageSize);
            List<EcardBranchUserUndoTask> ecardBranchUserUndoTaskList = ecardBranchEcardChartService.getUserUnDoTaskListByApplet(ecardBranchUserUndoTask);
            PageInfo pageInfo = new PageInfo(ecardBranchUserUndoTaskList);
            return ResponseModel.okToJSONArray(pageInfo.getTotal(), ecardBranchUserUndoTaskList);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResponseModel.error("操作失败,请联系管理员!");
        }
    }
}
